#!/usr/bin/python
#-*-coding:utf-8-*-
import server.send_cms_thread as sendThread
import server.get_accesstoken as accesstoken
import constant.constant_value as Constant
import dbutils.article_db_utils as articleDB
import dbutils.config_db_utils as configDB
import image.downImage as downImage
import image.server_file_upload as upload_image
import random,time,datetime,sys
from bs4 import BeautifulSoup as parserUtils
import image.file_deal as fileDeal
reload(sys)
#sys.path.append("../")
sys.setdefaultencoding('utf-8')

config_db = configDB.Config_DB()
article_db = articleDB.Article_DB()

def deal_article(access_token,article):
    soup = parserUtils(article);
    file_path_list = []
    uri = ""
        
    image_all =  soup.find_all("img",{"src":True})
    if len(image_all)>0:
        for image_item in image_all:
            image_src =  image_item['src']
            print image_src;
            image_name = str(image_src).split('/')[len(str(image_src).split('/'))-1]
            image_name,image_path = downImage.write_file(image_name, image_src)
            try:
                uri = upload_image.upload(image_path,access_token)
            except Exception as err:
                print err;
            file_path_list.append(image_path)
            if uri == "":
                pass;
            else:
                image_item['src'] = uri
                article = article.replace(image_src,uri)
                
    # 替换关键字
    article = article.replace("<u>中国养猪网</u>讯:","").replace("<u>中国养猪网</u>讯：","").replace("中国养<u>猪</u>网讯:","").replace("中国养<u>猪</u>网讯：","")
    
    for file_path_item in file_path_list:
        fileDeal.del_file(str(file_path_item))
        pass
    return article;

def process(aid, title, article, config):
    thread_access_token = accesstoken.get_access_token(Constant.api_username, Constant.api_password)
    
    newArticle = deal_article(thread_access_token,article) # 处理图片
        
    code = sendThread.send(title, newArticle, config.channel_id, config.type_id, config.cms_uid,config.name)
    if (code == 0):
        article_db.update_article_status(config.table_name, Constant.status_success, aid)
        print u"publish thread success:" + config.table_name + "-" + str(aid);
    else:
        article_db.update_article_status(config.table_name, Constant.status_thread_error, aid)
        print u"publish thread false:" + config.table_name + "-" + str(aid);
    
def thread_send():
    cur_pos = 0
    configs = config_db.get_configs() # 取发帖用户
        
    if len(configs) > 0:
        for config in configs:
            config.total_count = article_db.get_count(config.table_name, -1)
            config.status_wait = article_db.get_count(config.table_name, Constant.status_wait)
            config.status_success = article_db.get_count(config.table_name, Constant.status_success)
            config_db.update_configs(config)
            
        print u"get configs success start send.";
        while (True):
            try:
                limit = Constant.cms_api_count_limit - cur_pos # 当天剩余发帖数
                if limit > 0:
                    config_index = random.randint(0,len(configs)-1) # 随机选择某个频道发帖
                    config = configs[config_index]
                    
                    aid,title,article = article_db.get_article(config.table_name) # 取对应的帖子信息
                    
                    if len(article)>0:
                        process(aid, title, article, config)
                        cur_pos += 1
                        time.sleep(1)
                else:
                    cur_pos = 0
                    configs = config_db.get_configs()
                    for config in configs:
                        config.total_count = article_db.get_count(config.table_name, -1)
                        config.status_wait = article_db.get_count(config.table_name, Constant.status_wait)
                        config.status_success = article_db.get_count(config.table_name, Constant.status_success)
                        config_db.update_configs(config)
                    #计算当前时间到第二天0点的间隔小时数
                    dt = datetime.datetime.now()
                    hour = dt.hour #当前小时
                    time.sleep((24 - hour)* 3600)
            except Exception as err:
                print u"publish thread false:" + config.table_name + "-" + str(aid) + "-" + str(err);
                time.sleep(60)
    return;
      
if __name__ == "__main__":
    thread_send();